#!/usr/bin/env python
# -*- coding: utf-8 -*-


from hypium.action.device import UiDriver
from hypium.uidriver.uicomponent import IUiComponent
from hypium.uidriver.interface.uitree import ISelector
from hypium.model import Rect
from device import *


class API:
    def __init__(self, http_host, http_port):
        self.http_host = http_host
        self.http_port = http_port


    def get_image_filepath(device: str, filename: str) -> str:
        """获取设备截图的完整路径"""
        # 获取配置的图片目录
        images_dir = os.environ.get('IMAGES_DIR', os.path.abspath('./images'))
        # 确保设备目录存在
        device_dir = os.path.join(images_dir, device)
        os.makedirs(device_dir, exist_ok=True)
        return os.path.join(images_dir, device, filename)

    def call_get_device_list() -> dict:
        global hypium_drivers
        device_sn_list = list(hypium_drivers.keys())
        logging.debug(f'device_sn_list: {device_sn_list}')
        device_list = [Device(sn).to_dict() for sn in device_sn_list]
        return {"retval": 0, "result": {"devices": device_list}}

    def call_capture_screen(device: str, filename: str, area: Union[Rect, ISelector, IUiComponent] = None) -> dict:
        global hypium_drivers
        filepath = hypium_drivers[device].capture_screen(get_image_filepath(device, filename), True, area)
        logging.debug(f'screenshot filepath: {filepath}')
        global http_address
        global http_port
        if http_address is None or http_port is None:
            return {"retval": 1, "message": "http server not available"}
        image_url = f"http://{http_address}:{http_port}/images/{device}/{filename}"
        
        # Notify socket server that device is active (status update)
        notify_socket_server_device_status(device, "active")
        
        return {"retval": 0, "result": {"imageUrl": image_url}}

    def call_take_screenshot(device: str, mode: str = "key") -> dict:
        global hypium_drivers
        hypium_drivers[device].take_screenshot(mode)
        return {"retval": 0, "result": {}}

    DEVICE_API_REQUEST_HANDLER = {
        "get_device_list": call_get_device_list,
        "capture_screen": call_capture_screen,
        "take_screenshot": call_take_screenshot,
    }

    def init_hypium_drivers(self):
        stdout, stderr = subprocess.Popen(
            'hdc list targets',
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True).communicate()
        logging.debug(f'stdout: {stdout}')
        if stderr:
            logging.debug(f'stderr: {stderr}')
            return False
        device_sn_list = stdout.splitlines()
        device_sn_list = [device_sn for device_sn in device_sn_list if device_sn and device_sn != '[Empty]']
        for device_sn in device_sn_list:
            self.hypium_drivers[device_sn] = UiDriver.connect(device_sn=device_sn)
        logging.debug(f'hypium_drivers: {self.hypium_drivers}')
        return True